/*
  学习目标：容易踩坑点

*/

import React, { useEffect, useState } from 'react';
import Footer from './components/Footer';
import Header from './components/Header';
import Main from './components/Main';
import './styles/base.css';
import './styles/index.css';

export default function App() {
  const [list, setList] = useState([]);
  const [type, setType] = useState('all');

  // 💥 容易踩坑点
  // 1. 依赖项, 要先声明后使用
  // 2. 先写挂载后, 再写更新
  useEffect(() => {
    const list = JSON.parse(localStorage.getItem('todo-list-79') || '[]');
    setList(list);
  }, []);

  // 挂载更新二合一
  useEffect(() => {
    localStorage.setItem('todo-list-79', JSON.stringify(list));
  }, [list]);

  const handleDelById = (id) => {
    const newList = list.filter((item) => item.id !== id);
    setList(newList);
  };

  const handleUpdateById = (id) => {
    const newList = list.map((item) => {
      return {
        ...item,
        isDone: item.id !== id ? item.isDone : !item.isDone,
      };
    });

    setList(newList);
  };

  const handleAdd = (task) => {
    const newTask = { task, id: Date.now(), isDone: false };
    setList([newTask, ...list]);
  };

  const handleUpdateType = (type) => {
    setType(type);
  };

  const showList = list.filter((item) => {
    if (type === 'active') return !item.isDone;
    if (type === 'completed') return item.isDone;
    return true;
  });

  const handleCheckAll = (checked) => {
    const newList = list.map((item) => ({ ...item, isDone: checked }));
    setList(newList);
  };

  return (
    <section className="todoapp">
      <Header handleAdd={handleAdd} />
      <Main
        handleCheckAll={handleCheckAll}
        list={showList}
        handleDelById={handleDelById}
        handleUpdateById={handleUpdateById}
      />
      <Footer type={type} handleUpdateType={handleUpdateType} />
    </section>
  );
}
